package juc.c_021_01Interview;
/*
   Talk is cheap. Show me the code.
 */

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Date 2021/6/20
 * @Author liudl
 */
public class T04_NotifyFreeLock {
    volatile List lists = new ArrayList();

    public boolean add(Object o) {
        return lists.add(o);
    }

    public int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        T04_NotifyFreeLock t = new T04_NotifyFreeLock();
        final Object lock = new Object();
        new Thread(()->{
            synchronized (lock) {
                System.out.println("t2 start");
                if (t.size() != 5) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notify();
                System.out.println("t2 end");
            }
        },"t2").start();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            synchronized (lock) {
                System.out.println("t1 start");
                for (int i = 0; i < 10; i++) {
                    System.out.println(i);
                    t.add(i);
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (t.size() == 5) {
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println("t1 end");
            }
        },"t1").start();

    }
}
